<?php
namespace App\Modules\Package\Models;

use App\Library\OSS;
use App\Modules\Coupon\Models\FullReduction;
use App\Modules\Coupon\Models\FullReductionScope;
use App\Modules\Good\Models\GoodsDiscount;
use App\Modules\Good\Models\GoodsDiscountScope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 * Class GoodPackage
 * @package App\Modules\Package\Models
 * @property string $name
 * @property integer $shop_id
 * @property string $category
 * @property array $cover
 * @property string $video
 * @property integer $display_price
 * @property integer $price
 * @property string $description
 * @property array $service
 * @property integer $modelling
 * @property integer $photo
 * @property integer $truing
 * @property integer $sales_volume
 * @property integer $share_number
 * @property string $share_bg
 * @property integer $visitor
 * @property integer $prepay
 * @property integer $status
 * @property string $order_cover
 * @property int $is_free
 * @property string $hot_cover
 * @property string $recommend_cover
 * @property string $selected_cover
 * @property int $sort
 */
class GoodPackage extends Model
{
    const STATUS_ON = "on";
    const STATUS_OFF = "off";

    static public $statusShow = [
        self::STATUS_ON => '上架',
        self::STATUS_OFF => '下架',
    ];
    protected $fillable = [
        'shop_id',
        'name',
        'category',
        'cover',
        'video',
        'display_price',
        'price',
        'description',
        'service',
        'stock',
        'sales_volume',
        'share_number',
        'share_bg',
        'visitor',
        'sort',
        'modelling',
        'photo',
        'truing',
        'prepay',
        "status",
        "order_cover",
        'is_free',
        'hot_cover',
        'recommend_cover',
        'selected_cover',
        'discount_limit',
        'discount_amount',
        'end_time',
        'virtual_sales_volume',
        'is_balance_pay',//是否支持余额支付
        'is_recharge',//本商品是否为充值商品
        'recharge_money',//实际充值金额
        'tag_id',//服务标签
    ];

    protected $casts = [
        'cover' => 'array',
        'service' => 'array',
    ];

    public function getGiftShow()
    {
        $scope = GiftScope::query()
            ->where('package_id', $this->id)
            ->get();

        $gift = Gift::query()
            ->whereIn('id', $scope->pluck('gift_id')->all())
            ->get();

        if (is_null($gift)) {
            return null;
        }
        $content = $gift->pluck('content')->all();
        $libIds = [];
        foreach ($content as $item) {
            foreach ($item as $item2) {
                $libIds[] = $item2['id'];
            }
        }
        $attrValues = PackageAttrValue::query()
            ->whereIn('id', $libIds)
            ->get()
            ->keyBy('id');
        return $gift->map(function ($item) use ($attrValues) {
            $content = [];
            foreach ($item->content as $value) {
                $tmp = $attrValues->get($value['id']);
                if (!is_null($tmp)) {
                    $content[] = [
                        'id' => $tmp->id,
                        'attr_value_id' => $item->attr_value_id,
                        'attr_value' => $tmp->value,
                        'price' => $tmp->price,
                        'selling_price' => $tmp->selling_price,
                        'cover' => OSS::instance()->getUrl($tmp->cover),
                        'number' => $value['number'],
                    ];
                }
            }
            return [
                'id' => $item->id,
                'title' => $item->title,
                'content' => $content,
            ];
        });
    }

    public function getGift()
    {
        $scope = GiftScope::query()
            ->where('package_id', $this->id)
            ->get();

        $gift = Gift::query()
            ->whereIn('id', $scope->pluck('gift_id')->all())
            ->get();

        if (is_null($gift)) {
            return null;
        }

        $content = $gift->pluck('content')->all();
        $libIds = [];
        $numbers = [];
        foreach ($content as $item) {
            foreach ($item as $item2) {
                if (!isset($numbers[$item2['id']])) {
                    $numbers[$item2['id']] = $item2['number']?? 1;
                } else {
                    $numbers[$item2['id']] += $item2['number']?? 1;
                }
                $libIds[] = $item2['id'];
            }
        }
        $attrValue = PackageAttrValue::query()
            ->whereIn('id', $libIds)
            ->get()
            ->keyBy('id');
        $spec = PackageSpec::query()
            ->where('package_id', $this->id)
            ->whereIn('attr_value_id', $attrValue->pluck('id')->all())
            ->get();
        $attr = PackageAttr::query()
            ->whereIn('id', $attrValue->pluck('package_attr_id')->all())
            ->get()
            ->keyBy('id');
        $gift = $spec->map(function ($item) use ($attrValue, $attr, $numbers) {
            $tmp = $attrValue->get($item->attr_value_id);
            return [
                'id' => $item->id,
                'attr' => $attr->get($tmp->package_attr_id)->name,
                'attr_id' => $tmp->package_attr_id,
                'attr_value_id' => $item->attr_value_id,
                'attr_value' => $tmp->value,
                'price' => $tmp->selling_price,
                'selling_price' => $tmp->selling_price,
                'cover' => OSS::instance()->getUrl($tmp->cover),
                'number' => $numbers[$item->attr_value_id],
            ];
        })->values();
        return $gift;
    }

    public function getFullReduction($price)
    {
        $scope = FullReductionScope::query()
            ->where('type', self::class)
            ->where('link_id', $this->id)
            ->get();
        $reduction = FullReduction::query()
            ->whereIn('id', $scope->pluck('full_reduction_id')->all())
            ->where('limit', "<=", $price)
            ->orderBy('abatement', 'desc')
            ->first();
        if (is_null($reduction)) {
            return 0;
        }
        return $reduction->abatement * floor($price/$reduction->limit);
    }

    public function getDiscount($price)
    {
        $scope = GoodsDiscountScope::query()
            ->where('type', self::class)
            ->where('link_id', $this->id)
            ->get();
        $discount = GoodsDiscount::query()
            ->whereIn('id', $scope->pluck('goods_discount_id')->all())
            ->where('limit', "<=", $price)
            ->orderBy('ratio')
            ->first();
        if (is_null($discount)) {
            return 0;
        }
        return $price * (1 - ($discount->ratio / 100));
    }
}
